package msg;

import util.IntByteConverter;

public class UpdateMsg extends Msg {
	private byte type;
	private byte[] path;
	private byte[] value;

	public UpdateMsg() {
		this.type = Msg.UPDATE;
	}

	public UpdateMsg(byte[] path, byte[] value) {
		this();
		this.path = path;
		this.value = value;
	}

	public UpdateMsg(String path, String value) {
		this(path.getBytes(), value.getBytes());
	}

	public byte getType() {
		return type;
	}

	public void setType(byte type) {
		this.type = type;
	}

	public byte[] getPath() {
		return path;
	}

	public void setPath(byte[] path) {
		this.path = path;
	}

	public byte[] getValue() {
		return value;
	}

	public void setValue(byte[] value) {
		this.value = value;
	}

	@Override
	public byte[] encode() throws Exception {
		byte[] buffer = new byte[1 + 4 + 4 + this.path.length + this.value.length];

		buffer[0] = this.type;

		byte[] path_length = IntByteConverter.toByteArray(this.path.length);
		for (int i = 0; i < 4; i++) {
			buffer[i + 1] = path_length[i];
		}

		byte[] value_length = IntByteConverter.toByteArray(this.value.length);
		for (int i = 0; i < 4; i++) {
			buffer[i + 1 + 4] = value_length[i];
		}

		for (int i = 0; i < this.path.length; i++) {
			buffer[i + 1 + 4 + 4] = this.path[i];
		}

		for (int i = 0; i < this.value.length; i++) {
			buffer[i + 1 + 4 + 4 + this.path.length] = this.value[i];
		}

		return buffer;
	}

	@Override
	public void decode(byte[] buffer) throws Exception {
		this.type = buffer[0];
		if (this.type != Msg.UPDATE) {
			throw new Exception();
		}

		byte[] path_length = new byte[4];
		for (int i = 0; i < 4; i++) {
			path_length[i] = buffer[i + 1];
		}
		this.path = new byte[IntByteConverter.toInt(path_length)];

		byte[] value_length = new byte[4];
		for (int i = 0; i < 4; i++) {
			value_length[i] = buffer[i + 1 + 4];
		}
		this.value = new byte[IntByteConverter.toInt(value_length)];

		for (int i = 0; i < this.path.length; i++) {
			this.path[i] = buffer[i + 1 + 4 + 4];
		}

		for (int i = 0; i < this.value.length; i++) {
			this.value[i] = buffer[i + 1 + 4 + 4 + this.path.length];
		}
	}
}